import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePage();
}

class _MyHomePage extends State<MyHomePage> {
  ScrollController _controller = ScrollController(initialScrollOffset: 300);
  var _buttonFlag = false;

  @override
  void initState() {
    super.initState();
    // _controller.addListener(() {
    //   setState(() {
    //     _buttonFlag = _controller.offset >= 500;
    //   });
    // });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: const Center(
            child: Text("通过 controller 监听"),
          )),
      body: NotificationListener(
        onNotification: (ScrollNotification notification) {
          if (notification is ScrollStartNotification) {
            print("开始滚动 最大滚动范围：${notification.metrics.maxScrollExtent}");
          } else if (notification is ScrollEndNotification) {
            print("结束滚动 ${notification.metrics.pixels}");
            setState(() {
              _buttonFlag = notification.metrics.pixels >= 500;
            });
          } else if (notification is ScrollUpdateNotification) {
            print("正在滚动...  当前位置：${notification.metrics.pixels}");
          }

          return true;
        },
        child: ListView.builder(
          controller: _controller,
          itemCount: 30,
          itemBuilder: (context, index) {
            return ListTile(
                title: Text("联系人 $index"), leading: Icon(Icons.person));
          },
        ),
      ),
      floatingActionButton: _buttonFlag
          ? FloatingActionButton(
        onPressed: () => _controller.animateTo(0,
            duration: Duration(seconds: 1), curve: Curves.easeIn),
        child: Icon(Icons.arrow_upward),
      )
          : null,
    );
  }
}
